package com.app.manager;

import android.os.AsyncTask;

import com.app.constant.Email163;
import com.app.constant.EmailAliyun;
import com.app.constant.EmailSina;
import com.app.constant.EmailSohu;
import com.app.constant.EmailYeah;
import com.app.http.HttpDataApi;
import com.app.http.HttpDataLoader;
import com.app.model.bean.SenderBean;
import com.app.model.bean.TaskBean;
import com.app.model.response.ResObj;
import com.app.utils.SendResultUtil;
import com.app.utils.StringUtil;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * Created by Administrator on 2017/6/18.
 */

public class MailSender implements HttpDataApi.OnRequestCallback {

    private static final String LOG_TAG = MailSender.class.getSimpleName();

    public String DNS = Email163.class.getSimpleName();
    public String NAME = "";
    public String PASSWORD = "";
    public String HOST = Email163.HOST;
    public String PORT = Email163.PORT;
    public String AUTH = Email163.AUTH;
    public String STARTTLS_ENABLE = Email163.STARTTLS_ENABLE;
    public String FALLBACK = Email163.FALLBACK;
    public String DEBUG = Email163.DEBUG;
    public String CLASS = Email163.CLASS;

    private HttpDataLoader dataLoader;

    private TaskBean task;

    public static MailSender getInstance() {
        return InstanceHolder.instance;
    }

    private MailSender() {
        dataLoader = new HttpDataLoader(this);
    }

    @Override
    public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {

    }

    @Override
    public void onRequestError(String url, int statusCode, String error) {

    }

    private static class InstanceHolder {
        private static MailSender instance = new MailSender();
    }

    public interface OnSendResult {
        void onSendSuccess(TaskBean taskBean);

        void onSendFail(TaskBean taskBean, Exception e);
    }

    class MailTask extends AsyncTask<Void, Void, Boolean> {

        private MimeMessage mimeMessage;

//        private OnSendResult onSendResult;


        public MailTask(MimeMessage mimeMessage) {
            this.mimeMessage = mimeMessage;
        }
//        public MailTask(MimeMessage mimeMessage, OnSendResult onSendResult) {
//            this.mimeMessage = mimeMessage;
//            this.onSendResult = onSendResult;
//        }

        @Override
        protected Boolean doInBackground(Void... voids) {

            try {
                Transport.send(mimeMessage);
//                if (onSendResult != null) {
//                    onSendResult.onSendSuccess(task);
//                }
                SendResultUtil.getInstance().onSendSuccess(task);
                return Boolean.TRUE;
            } catch (MessagingException e) {
                e.printStackTrace();
//                if (onSendResult != null) {
//                    onSendResult.onSendFail(task, e);
//                }
                SendResultUtil.getInstance().onSendFail(task, e);
                return Boolean.FALSE;
            }
        }
    }


    public void sendMail(TaskBean task) {
        this.task = task;
        MimeMessage mimeMessage = createMessage(task);
        MailTask mailTask = new MailTask(mimeMessage);
        mailTask.execute();
    }

    private MimeMessage createMessage(TaskBean task) {

        Session session = Session.getInstance(getProperties(task), getAuthenticator(task.getSender()));
        MimeMessage mimeMessage = new MimeMessage(session);
        try {
            mimeMessage.setFrom(new InternetAddress(task.getSender().getName(), task.getEmail().getTitle()));
            List<String> receivers = task.getReceivers();
            InternetAddress[] addresses = new InternetAddress[receivers.size() + 1];
            addresses[0] = new InternetAddress(task.getSender().getName());
            for (int i = 1; i < task.getReceivers().size() + 1; i++) {
                addresses[i] = new InternetAddress(receivers.get(i - 1));
            }
            mimeMessage.setRecipients(Message.RecipientType.TO, addresses);
            mimeMessage.setSubject(task.getEmail().getTitle());
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setContent(task.getEmail().getContent(), "text/html;charset=UTF-8");
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(textPart);
            mimeMessage.setContent(multipart);
            mimeMessage.setSentDate(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mimeMessage;
    }


//    public void sendMail(final String title, final String content,  List<String> addressList) {
//        MimeMessage mimeMessage = createMessage(title, content, addressList);
//        MailTask mailTask = new MailTask(mimeMessage);
//        mailTask.execute();
//    }
//
//    public void sendMailWithFile(String title, String content, String filePath,  ArrayList<String> addressList) {
//        MimeMessage mimeMessage = createMessage(title, content, addressList);
//        appendFile(mimeMessage, filePath);
//        MailTask mailTask = new MailTask(mimeMessage);
//        mailTask.execute();
//    }
//
//    public void sendMailWithMultiFile(String title, String content,  ArrayList<String> addressList, List<String> pathList) {
//        MimeMessage mimeMessage = createMessage(title, content, addressList);
//        appendMultiFile(mimeMessage, pathList);
//        MailTask mailTask = new MailTask(mimeMessage);
//        mailTask.execute();
//    }


    private Authenticator getAuthenticator(final SenderBean sender) {
        return new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(sender.getName(), sender.getPassword());
            }
        };
    }


//    private Authenticator getAuthenticator() {
//        return new Authenticator() {
//            @Override
//            protected PasswordAuthentication getPasswordAuthentication() {
//                return new PasswordAuthentication(NAME, PASSWORD);
//            }
//        };
//    }

//    private MimeMessage createMessage(String title, String content, List<String> addressList) {
//
//        Session session = Session.getInstance(getProperties(), getAuthenticator());
//        MimeMessage mimeMessage = new MimeMessage(session);
//        try {
//            mimeMessage.setFrom(new InternetAddress(NAME));
//            InternetAddress[] addresses = new InternetAddress[addressList.size()];
//            for (int i = 0; i < addressList.size(); i++) {
//                addresses[i] = new InternetAddress(addressList.get(i));
//            }
//            mimeMessage.setRecipients(Message.RecipientType.TO, addresses);
//            mimeMessage.setSubject(title);
//            MimeBodyPart textPart = new MimeBodyPart();
//            textPart.setContent(content, "text/html;charset=UTF-8");
//            Multipart multipart = new MimeMultipart();
//            multipart.addBodyPart(textPart);
//            mimeMessage.setContent(multipart);
//            mimeMessage.setSentDate(new Date());
//        } catch (MessagingException e) {
//            e.printStackTrace();
//        }
//        return mimeMessage;
//    }
//
//
//    public void changeAccount() {
//        if (DNS.equals(Email163.class.getSimpleName())) {
//            if (Email163.index < Email163.names.length - 1) {
//                Email163.index++;
//                NAME = Email163.names[Email163.index];
//                PASSWORD = Email163.pwds[Email163.index];
//                HOST = Email163.HOST;
//                PORT = Email163.PORT;
//                AUTH = Email163.AUTH;
//                STARTTLS_ENABLE = Email163.STARTTLS_ENABLE;
//                FALLBACK = Email163.FALLBACK;
//                DEBUG = Email163.DEBUG;
//                CLASS = Email163.CLASS;
//            } else {
//                DNS = EmailSohu.class.getSimpleName();
//                NAME = EmailSohu.names[EmailSohu.index];
//                PASSWORD = EmailSohu.pwds[EmailSohu.index];
//                HOST = Email163.HOST;
//                PORT = Email163.PORT;
//                AUTH = Email163.AUTH;
//                STARTTLS_ENABLE = Email163.STARTTLS_ENABLE;
//                FALLBACK = Email163.FALLBACK;
//                DEBUG = Email163.DEBUG;
//                CLASS = Email163.CLASS;
//            }
//        } else if (DNS.equals(EmailSohu.class.getSimpleName())) {
//            if (EmailSohu.index < EmailSohu.names.length - 1) {
//                EmailSohu.index++;
//                NAME = EmailSohu.names[EmailSohu.index];
//                PASSWORD = EmailSohu.pwds[EmailSohu.index];
//                HOST = EmailSohu.HOST;
//                PORT = EmailSohu.PORT;
//                AUTH = EmailSohu.AUTH;
//                STARTTLS_ENABLE = EmailSohu.STARTTLS_ENABLE;
//                FALLBACK = EmailSohu.FALLBACK;
//                DEBUG = EmailSohu.DEBUG;
//                CLASS = EmailSohu.CLASS;
//            } else {
//                DNS = EmailSohu.class.getSimpleName();
//                NAME = EmailSohu.names[EmailSohu.index];
//                PASSWORD = EmailSohu.pwds[EmailSohu.index];
//                HOST = EmailSohu.HOST;
//                PORT = EmailSohu.PORT;
//                AUTH = EmailSohu.AUTH;
//                STARTTLS_ENABLE = EmailSohu.STARTTLS_ENABLE;
//                FALLBACK = EmailSohu.FALLBACK;
//                DEBUG = EmailSohu.DEBUG;
//                CLASS = EmailSohu.CLASS;
//            }
//        }
//    }

    // 获取properties信息，如果需要切换账号则切换到下一个账号
    private Properties getProperties(TaskBean taskBean) {
        Properties properties = new Properties();
        if (taskBean == null || taskBean.getSender() == null) {
            return null;
        }
        String name = taskBean.getSender().getName();
        String title = taskBean.getEmail().getTitle();
        if (!StringUtil.isEmpty(name)) {
            properties.put("mail.smtp.user", title);
            if (name.contains("163.com")) {
                properties.put("mail.smtp.host", Email163.HOST);
                properties.put("mail.smtp.port", Email163.PORT);
                properties.put("mail.smtp.auth", Email163.AUTH);
                properties.put("mail.smtp.starttls.enable", Email163.STARTTLS_ENABLE);
                properties.put("mail.smtp.debug", Email163.DEBUG);
                properties.put("mail.smtp.socketFactory.port", Email163.PORT);
                properties.put("mail.smtp.socketFactory.fallback", Email163.FALLBACK);
                properties.put("mail.smtp.socketFactory.class", Email163.CLASS);
            } else if (name.contains("sohu.com")) {
                properties.put("mail.smtp.host", EmailSohu.HOST);
                properties.put("mail.smtp.port", EmailSohu.PORT);
                properties.put("mail.smtp.auth", EmailSohu.AUTH);
                properties.put("mail.smtp.starttls.enable", EmailSohu.STARTTLS_ENABLE);
                properties.put("mail.smtp.debug", EmailSohu.DEBUG);
                properties.put("mail.smtp.socketFactory.port", EmailSohu.PORT);
                properties.put("mail.smtp.socketFactory.fallback", EmailSohu.FALLBACK);
                properties.put("mail.smtp.socketFactory.class", EmailSohu.CLASS);
            } else if (name.contains("sina.com")) {
                properties.put("mail.smtp.host", EmailSina.HOST);
                properties.put("mail.smtp.port", EmailSina.PORT);
                properties.put("mail.smtp.auth", EmailSina.AUTH);
                properties.put("mail.smtp.starttls.enable", EmailSina.STARTTLS_ENABLE);
                properties.put("mail.smtp.debug", EmailSina.DEBUG);
                properties.put("mail.smtp.socketFactory.port", EmailSina.PORT);
                properties.put("mail.smtp.socketFactory.fallback", EmailSina.FALLBACK);
                properties.put("mail.smtp.socketFactory.class", EmailSina.CLASS);
            } else if (name.contains("yeah.net")) {
                properties.put("mail.smtp.host", EmailYeah.HOST);
                properties.put("mail.smtp.port", EmailYeah.PORT);
                properties.put("mail.smtp.auth", EmailYeah.AUTH);
                properties.put("mail.smtp.starttls.enable", EmailYeah.STARTTLS_ENABLE);
                properties.put("mail.smtp.debug", EmailYeah.DEBUG);
                properties.put("mail.smtp.socketFactory.port", EmailYeah.PORT);
                properties.put("mail.smtp.socketFactory.fallback", EmailYeah.FALLBACK);
                properties.put("mail.smtp.socketFactory.class", EmailYeah.CLASS);
            } else if (name.contains("aliyun.com")) {
                properties.put("mail.smtp.host", EmailAliyun.HOST);
                properties.put("mail.smtp.port", EmailAliyun.PORT);
                properties.put("mail.smtp.auth", EmailAliyun.AUTH);
                properties.put("mail.smtp.starttls.enable", EmailAliyun.STARTTLS_ENABLE);
                properties.put("mail.smtp.debug", EmailAliyun.DEBUG);
                properties.put("mail.smtp.socketFactory.port", EmailAliyun.PORT);
                properties.put("mail.smtp.socketFactory.fallback", EmailAliyun.FALLBACK);
                properties.put("mail.smtp.socketFactory.class", EmailAliyun.CLASS);
            }
        }
        return properties;
    }

    private void appendFile(MimeMessage message, String filePath) {
        try {
            Multipart multipart = (Multipart) message.getContent();
            MimeBodyPart filePart = new MimeBodyPart();
            filePart.attachFile(filePath);
            multipart.addBodyPart(filePart);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    private void appendMultiFile(MimeMessage message, List<String> pathList) {
        try {
            Multipart multipart = (Multipart) message.getContent();
            for (String path : pathList) {
                MimeBodyPart filePart = new MimeBodyPart();
                filePart.attachFile(path);
                multipart.addBodyPart(filePart);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
